package com.hengyue.system.service.impl;

import com.hengyue.exception.ServiceException;
import com.hengyue.system.domain.entity.SysPost;
import com.hengyue.system.repository.SysPostRepository;
import com.hengyue.system.service.ISysPostService;
import jakarta.persistence.criteria.Predicate;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SysPostServiceImpl implements ISysPostService {

    private final SysPostRepository sysPostRepository;

    @Override
    public Page<SysPost> selectPostList(SysPost post, Pageable pageable) {
        return sysPostRepository.findAll(getSpecification(post), pageable);
    }

    @Override
    public List<SysPost> selectPostList(SysPost post) {
        return sysPostRepository.findAll(getSpecification(post));
    }

    /**
     * 查询所有岗位
     *
     * @return 岗位列表
     */
    @Override
    public List<SysPost> selectPostAll() {
        return sysPostRepository.findAll();
    }

    @Override
    public SysPost selectPostById(Long postId) {
        return sysPostRepository.findById(postId).orElse(null);
    }

    @Override
    public List<Long> selectPostListByUserId(Long userId) {
        // 实现根据用户ID查询岗位ID列表的逻辑
        // 这里可以根据具体需求实现，例如从用户岗位关联表中查询
        return null;
    }

   /* @Override
    public boolean checkPostNameUnique(SysPost post) {
        return false;
    }*/

    //@Override
    /*public boolean checkPostCodeUnique(SysPost post) {
        return false;
    }*/

    @Override
    public boolean checkPostUnique(SysPost post) {
        Long configId = post.getId() == null ? -1L : post.getId();
        // 查询是否存在相同dictType或code的记录（排除当前记录）
        boolean exists = sysPostRepository.exists((root, query, cb) ->
                cb.and(
                        cb.or(
                                cb.equal(root.get("postCode"), post.getPostCode()),
                                cb.equal(root.get("postName"), post.getPostName())
                        ),
                        cb.notEqual(root.get("id"), configId)
                )
        );
        return !exists;
    }

    @Override
    public int countUserPostById(Long postId) {
        // 实现查询逻辑，根据postId查询用户岗位关联表中的记录数量
         return 0;
    }

    @Override
    public void deletePostById(Long postId) {
        sysPostRepository.deleteById(postId);
    }

    @Override
    public void deletePostByIds(Long[] postIds) {
        for (Long postId : postIds)
        {
            SysPost post = selectPostById(postId);
            if (countUserPostById(postId) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
         sysPostRepository.deleteAllByIdInBatch(Arrays.asList(postIds));
    }

    @Override
    public void insertPost(SysPost post) {
        sysPostRepository.save(post);
    }

    @Override
    public void updatePost(SysPost post) {
        sysPostRepository.save(post);
    }

    @Override
    public Specification<SysPost> getSpecification(SysPost sysPost) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StringUtils.hasText(sysPost.getPostCode())) {
                predicates.add(cb.like(root.get("postCode"), "%" + sysPost.getPostCode() + "%"));
            }
            if (StringUtils.hasText(sysPost.getStatus())) {
                predicates.add(cb.equal(root.get("status"), sysPost.getStatus()));
            }
            if (StringUtils.hasText(sysPost.getPostName())) {
                predicates.add(cb.like(root.get("postName"), "%" + sysPost.getPostName() + "%"));
            }


            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }


}
